package me.numark.activities;

import com.google.gson.Gson;
import com.squareup.picasso.Picasso;
import com.tencent.mm.sdk.modelmsg.SendAuth;

import android.app.Activity;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import me.numark.R;
import me.numark.fragments.InputDialogFragment;
import me.numark.model.AvatarResponse;
import me.numark.model.LogInResponse;
import me.numark.model.User;
import me.numark.net.BaseResponse;
import me.numark.net.NetworkConstants;
import me.numark.net.RequestServerTask;
import me.numark.net.UploadImageRequest;
import me.numark.utils.Constants;
import me.numark.utils.FileUtils;
import me.numark.utils.Global;
import me.numark.utils.HttpUtil;
import me.numark.utils.ImageUtils;
import me.numark.utils.Settings;
import me.numark.utils.Utils;
import me.numark.view.CircleImageView;

/**
 * Created by ytian on 15/8/8.
 */
public class EditProfileActivity extends AuthenticatorActivity implements View.OnClickListener,
        InputDialogFragment.InputDialogInterface {
    @Bind(R.id.right_text)
    TextView rightText;

    @Bind(R.id.settings_list)
    LinearLayout mList;

    private CircleImageView avatar;

    private TextView nickEdit;

    private TextView desEdit;

    private TextView genderView;

    private TextView birthdayView;

    private static final int REQUEST_EDIT_NICK = 1001;

    private static final int REQUEST_EDIT_DES = 1002;

    private static final int REQUEST_VERIFY_MOBILE = 1003;

    final static int[] titles = new int[]{R.string.avatar, R.string.nick,
            R.string.gender, R.string.my_signature, R.string.birthday};

    final static int[] bindTitles = new int[]{R.string.mobile_number, R.string.qq, R.string
            .wechat, R.string.weibo};
    private Bitmap bitmap;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        activity_layout_res = R.layout.activity_edit_profile;
        super.onCreate(savedInstanceState);
        rightText.setText(R.string.finish);
        rightText.setVisibility(View.GONE);
        rightText.setOnClickListener(this);
        if (titleTextView != null) {
            titleTextView.setText(R.string.personal_center);
        }
        addProfileLines();
        addBindTitle();
        addBindLines();
        backInToolbar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        updateProfile();
    }

    private void addBindTitle() {
        View view = getLayoutInflater().inflate(R.layout.bind_title, mList, false);
        mList.addView(view);
    }

    private void addProfileLines() {
        for (int i = 0; i < titles.length; i++) {
            addLine(i);
        }
    }

    private void addBindLines() {
        for (int i = 0; i < bindTitles.length; i++) {
            addBindLine(i);
        }
    }

    private List<ViewHolder> mViewHolders = new ArrayList<>();
    private void addBindLine(int index) {
        View line = getLayoutInflater().inflate(R.layout.edit_profile_list_item, mList, false);
        ViewHolder vh = new ViewHolder(line);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams
                .MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        vh.title.setText(bindTitles[index]);
        vh.content.setInputType(InputType.TYPE_NULL);
        vh.arrow.setVisibility(View.GONE);
        vh.bind.setVisibility(View.VISIBLE);
        updateBindText(index, vh);
        if (index == bindTitles.length - 1) {
            //hide the last divider
            vh.divider.setVisibility(View.GONE);
        }
        int id = 1000 + index;
        line.setId(id);
        line.setOnClickListener(this);
        mViewHolders.add(vh);
        mList.addView(line, lp);
    }

    private void updateBindText(int index, ViewHolder vh) {
        String content = getBindContent(index);
        if (TextUtils.isEmpty(content)) {
            vh.content.setText(null);
            vh.bind.setText(R.string.bind);
            vh.bind.setTextColor(getResources().getColor(R.color.btn_green));
        } else {

            vh.bind.setText(R.string.unbind);
            vh.bind.setTextColor(getResources().getColor(R.color.gray1));
            vh.content.setText(content);
        }
    }

    @Nullable
    private String getBindContent(int index) {
        String content = null;
        //Log.d("CurrentUser",Global.currentUser.toString());
        switch (index) {

            case 0:
                content = Global.currentUser.phone;
                break;
            case 1:
                content = Global.currentUser.QQ;
                break;
            case 2:
                content = Global.currentUser.weixin;
                break;
            case 3:
                content = Global.currentUser.weibo;
                break;
        }
        return content;
    }

    private void addLine(int index) {
        View line = getLayoutInflater().inflate(R.layout.edit_profile_list_item, mList, false);
        ViewHolder vh = new ViewHolder(line);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams
                .MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        vh.title.setText(titles[index]);
        switch (index) {
            case 0:
                vh.avatar.setVisibility(View.VISIBLE);
                avatar = vh.avatar;
                if (!TextUtils.isEmpty(Global.currentUser.pic)) {
                    Picasso.with(this).load(Global.currentUser.pic).into(vh.avatar);
                }
                vh.arrow.setVisibility(View.INVISIBLE);
                break;
            case 1:
                vh.content.setText(Global.currentUser.nick);
                nickEdit = vh.content;
                break;
            case 2:
                vh.content.setText(Global.currentUser.getGenderText());
                genderView = vh.content;
                break;
            case 3:
                vh.content.setText(Global.currentUser.des);
                desEdit = vh.content;
                break;
            case 4:
                if (!TextUtils.isEmpty(Global.currentUser.birthday)) {
                    if (!Global.currentUser.birthday.equals("0")) {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        try {
                            Date date = sdf.parse(Global.currentUser.birthday);
                            birthday = sdf.format(date);
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        vh.content.setText(birthday);
                    }else {
                        vh.content.setText("1970-01-01");
                    }

                }else {
                    vh.content.setText("1970-01-01");
                }
                birthdayView = vh.content;
                break;
        }
        line.setId(100 + index);
        line.setOnClickListener(this);
        mList.addView(line, lp);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.right_text:
                updateProfile();
                break;
            case 100:   //avatar
                ImageUtils.takeOrChoosePhoto(this, ImageUtils.TAKE_OR_CHOOSE_PHOTO);
                break;
            case 101:   //nick
                showNickDialog();
                break;
            case 102:   //gender
                showGenderDialog();
                break;
            case 103:   //desc
                showDescDialog();
                break;
            case 104:   //birthday
                showBirthdayDialog();
                break;
            case 1000:  //bind/unbind mobile
                if (Global.currentUser.is_phone) {
                    unbindPhone();
                } else {
                    bindPhone();
                }
                break;
            case 1001:  //bind/unbind QQ
                handleQQ();
                break;
            case 1002:  //bind/unbind wechat
                handleWeChat();
                break;
            case 1003:  //bind/unbind weibo
                handleWeibo();
                break;
        }
    }

    private void handleQQ() {
        int titleId = Global.currentUser.is_QQ ? R.string.unbind_qq_title : R.string.bind_qq_title;
        int msgId = Global.currentUser.is_QQ ? R.string.unbind_qq_msg : R.string.bind_qq_msg;
        /*new AlertDialog.Builder(this).setTitle(titleId).setMessage(msgId).setPositiveButton(R
                .string.good, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (mTencent == null) {
                    Utils.showToast(R.string.qq_not_installed);
                    return;
                }
                mTencent.login(EditProfileActivity.this, "get_user_info", EditProfileActivity.this);
            }
        }).setNegativeButton(R.string.cancel, null).show();*/
        final Dialog lDialog = new Dialog(this,R.style.dialog_style);
        lDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        lDialog.setContentView(R.layout.r_okcanceldialogview);
        TextView txtMsg = (TextView) lDialog.findViewById(R.id.dialog_message);
        txtMsg.setText(getString(msgId));
        TextView txtTitle = (TextView)lDialog.findViewById(R.id.dialog_title);
        txtTitle.setVisibility(View.VISIBLE);
        txtTitle.setText(getString(titleId));
        ((Button) lDialog.findViewById(R.id.cancel))
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        lDialog.dismiss();
                    }
                });
        ((Button) lDialog.findViewById(R.id.ok))
                .setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        lDialog.dismiss();
                        if (mTencent == null) {
                            Utils.showToast(R.string.qq_not_installed);
                            return;
                        }
                        mTencent.login(EditProfileActivity.this, "get_user_info", EditProfileActivity.this);
                    }
                });
        lDialog.show();
    }

    private void handleWeibo() {
        int titleId = isWeiboUser() ? R.string.unbind_weibo_title : R.string.bind_weibo_title;
        int msgId = isWeiboUser() ? R.string.unbind_weibo_msg : R.string.bind_weibo_msg;
       /* new AlertDialog.Builder(this).setTitle(titleId).setMessage(msgId).setPositiveButton(R
                .string.good, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                mSsoHandler.authorize(EditProfileActivity.this);
            }
        }).setNegativeButton(R.string.cancel, null).show();*/
        final Dialog lDialog = new Dialog(this,R.style.dialog_style);
        lDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        lDialog.setContentView(R.layout.r_okcanceldialogview);
        TextView txtMsg = (TextView) lDialog.findViewById(R.id.dialog_message);
        txtMsg.setText(getString(msgId));
        TextView txtTitle = (TextView)lDialog.findViewById(R.id.dialog_title);
        txtTitle.setVisibility(View.VISIBLE);
        txtTitle.setText(getString(titleId));
        ((Button) lDialog.findViewById(R.id.cancel))
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        lDialog.dismiss();
                    }
                });
        ((Button) lDialog.findViewById(R.id.ok))
                .setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        lDialog.dismiss();
                        mSsoHandler.authorize(EditProfileActivity.this);
                    }
                });
        lDialog.show();
    }

    private void handleWeChat() {
        int titleId = isWeChatUser() ? R.string.unbind_wechat_title : R.string.bind_wechat_title;
        int msgId = isWeChatUser() ? R.string.unbind_wechat_msg : R.string.bind_wechat_msg;
        /*new AlertDialog.Builder(this).setTitle(titleId).setMessage(msgId).setPositiveButton(R
                .string.good, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (Global.mWxApi.isWXAppInstalled() && Global.mWxApi.isWXAppSupportAPI()) {
                    final SendAuth.Req req = new SendAuth.Req();
                    req.scope = "snsapi_userinfo";
                    req.state = "none";
                    Global.mWxApi.sendReq(req);
                } else {
                    Utils.showToast(R.string.weixin_oauth_failed);
                }
            }
        }).setNegativeButton(R.string.cancel, null).show();*/
        final Dialog lDialog = new Dialog(this,R.style.dialog_style);
        lDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        lDialog.setContentView(R.layout.r_okcanceldialogview);
        TextView txtMsg = (TextView) lDialog.findViewById(R.id.dialog_message);
        txtMsg.setText(getString(msgId));
        TextView txtTitle = (TextView)lDialog.findViewById(R.id.dialog_title);
        txtTitle.setVisibility(View.VISIBLE);
        txtTitle.setText(getString(titleId));
        ((Button) lDialog.findViewById(R.id.cancel))
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        lDialog.dismiss();
                    }
                });
        ((Button) lDialog.findViewById(R.id.ok))
                .setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        lDialog.dismiss();
                        if (Global.mWxApi.isWXAppInstalled() && Global.mWxApi.isWXAppSupportAPI()) {
                            final SendAuth.Req req = new SendAuth.Req();
                            req.scope = "snsapi_userinfo";
                            req.state = "none";
                            Global.mWxApi.sendReq(req);
                        } else {
                            Utils.showToast(R.string.weixin_oauth_failed);
                        }
                    }
                });
        lDialog.show();
    }

    private void bindPhone() {
        Intent intent = new Intent(this, RegisterActivity.class);
        intent.putExtra("verify_only", true);
        startActivityForResult(intent, REQUEST_VERIFY_MOBILE);
    }

    private void unbindPhone() {
        /*new AlertDialog.Builder(this).setTitle(R.string.about_to_unbind_phone).setMessage(R
                .string.unbind_phone_hint).setPositiveButton(R.string.good, new DialogInterface
                .OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                afterLogin(VALUE_APP, Global.currentUser.phone, null);
            }
        }).setNegativeButton(R.string.cancel, null).show();*/
        final Dialog lDialog = new Dialog(this,R.style.dialog_style);
        lDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        lDialog.setContentView(R.layout.r_okcanceldialogview);
        TextView txtMsg = (TextView) lDialog.findViewById(R.id.dialog_message);
        txtMsg.setText(getString(R.string.unbind_phone_hint));
        TextView txtTitle = (TextView)lDialog.findViewById(R.id.dialog_title);
        txtTitle.setVisibility(View.VISIBLE);
        txtTitle.setText(getString(R.string.about_to_unbind_phone));
        ((Button) lDialog.findViewById(R.id.cancel))
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        lDialog.dismiss();
                    }
                });
        ((Button) lDialog.findViewById(R.id.ok))
                .setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        lDialog.dismiss();
                        afterLogin(VALUE_APP, Global.currentUser.phone, null);
                    }
                });
        lDialog.show();
    }

    private void updateBindingStatus(final String url, final Map<String, Object> params) {
        new RequestServerTask<LogInResponse>(LogInResponse.class) {

            @Override
            protected String requestServer() {
                /*Log.d("type",params.get("type").toString());
                Log.d("cellphone",params.get("cellphone").toString());*/
                return HttpUtil.post(url, params);
            }

            @Override
            protected void onSuccess(LogInResponse result) {
                int uid = Global.getCurrentUid();
                String token = Global.currentUser.token;
                String p_nick = Global.currentUser.p_nick;
                Settings.delUser(String.valueOf(uid));
                Utils.showToast(R.string.unbind_success);
                Settings.setCurrentUid(0);
                Global.currentUser = null;
                saveUserInfo(result,token,p_nick);

              /*  User user = Global.currentUser;
                user.QQ = result.data.QQ;
                user.email = result.data.email;
                user.phone = result.data.phone;
                user.weibo = result.data.weibo;
                user.weixin = result.data.weixin;

                Settings.saveUser(user);
                Global.currentUser = user;
                Settings.setCurrentUid(user.uid);*/

                /*user.is_QQ = result.data.is_QQ;
                user.is_weibo = result.data.is_weibo;
                user.is_email = result.data.is_email;
                user.is_phone = result.data.is_phone;
                user.is_weixin = result.data.is_weixin;*/

                /*user.friend_type = result.data.friend_type;
                user.from_type = result.data.from_type;
                user.is_QQ = result.data.is_QQ;
                user.is_at = result.data.is_at;
                user.is_comment = result.data.is_comment;
                user.is_dialog = result.data.is_dialog;
                user.is_email = result.data.is_email;
                user.is_fans = result.data.is_fans;
                user.is_follow = result.data.is_follow;
                user.is_forward = result.data.is_forward;
                user.is_like = result.data.is_like;
                user.is_mine = result.data.is_mine;
                user.is_phone = result.data.is_phone;*/

                //Log.d("CurrentUser", Global.currentUser.toString());
                for (int i = 0; i < mViewHolders.size(); i++) {
                    updateBindText(i, mViewHolders.get(i));
                }

            }
        }.start();
    }

    protected void saveUserInfo(LogInResponse result,String token,String p_nick) {
        result.data.token = token;
        result.data.p_nick = p_nick;
        Settings.saveUser(result.data);
        Global.currentUser = result.data;
        Settings.setCurrentUid(result.data.uid);
    }

    private Date tmpBirthday = new Date();
    private String birthday;

    private void showBirthdayDialog() {
        LinearLayout dialogContent = (LinearLayout) View.inflate(this, R.layout
                .fragment_date_picker, null);
        DatePicker datePicker = (DatePicker) dialogContent.getChildAt(0);
        resetBirthday();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(tmpBirthday);
        datePicker.init(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get
                (Calendar.DAY_OF_MONTH), new DatePicker.OnDateChangedListener() {

            @Override
            public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                Calendar calendar = Calendar.getInstance();
                calendar.set(Calendar.YEAR, year);
                calendar.set(Calendar.MONTH, monthOfYear);
                calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                tmpBirthday = calendar.getTime();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                birthday = sdf.format(tmpBirthday);
            }
        });
        new AlertDialog.Builder(this)
                .setTitle(R.string.set_birthday)
                .setView(dialogContent)
                .setPositiveButton(R.string.good, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        Global.currentUser.birthday = birthday;
                        birthdayView.setText(birthday);
                    }
                }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                resetBirthday();
            }
        }).show();
    }

    private void resetBirthday() {
        if (!TextUtils.isEmpty(Global.currentUser.birthday)) {
            if (!Global.currentUser.birthday.equals("0")) {
                //tmpBirthday = new Date(Global.currentUser.birthday);
                birthday = Global.currentUser.birthday;
            }
        }
    }

    private void showDescDialog() {
        InputDialogFragment descFragment = InputDialogFragment.newInstance(getString(R
                .string.edit_desc), desEdit.getText().toString(), getString(R.string
                .new_desc_hint), null, REQUEST_EDIT_DES);
        descFragment.show(getFragmentManager(), "desc");
    }

    private void showNickDialog() {
        InputDialogFragment nickFragment = InputDialogFragment.newInstance(getString(R
                .string.edit_nick), nickEdit.getText().toString(), getString(R.string
                .new_nick_hint), null, REQUEST_EDIT_NICK);
        nickFragment.show(getFragmentManager(), "nick");
    }

    private void showGenderDialog() {

        /*new AlertDialog.Builder(this).setTitle(R.string.choose_gender)
                .setSingleChoiceItems(new String[]{"女", "男"}, 0, new DialogInterface
                        .OnClickListener() {


                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                            case 0:
                                genderView.setText("女");
                                break;
                            case 1:
                                genderView.setText("男");
                                break;
                        }
                        dialog.dismiss();
                        Global.currentUser.sex = User.getGenderValue(genderView.getText()
                                .toString());
                    }
                })
                .setPositiveButton(R.string.cancel, null).show();*/
        final Dialog lDialog = new Dialog(this,R.style.dialog_style);
        lDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        lDialog.setContentView(R.layout.r_okcanceldialogview);
        TextView dialogMessage = (TextView) lDialog.findViewById(R.id.dialog_message);
        dialogMessage.setVisibility(View.GONE);
        TextView dialogTitle = (TextView) lDialog.findViewById(R.id.dialog_title);
        dialogTitle.setVisibility(View.VISIBLE);
        dialogTitle.setText(getString(R.string.choose_gender));
        RadioGroup dialogRadioGroup = (RadioGroup) lDialog.findViewById(R.id.dialog_radiogroup);
        dialogRadioGroup.setVisibility(View.VISIBLE);
        View dialogView = lDialog.findViewById(R.id.dialog_devider);
        dialogView.setVisibility(View.GONE);
        Button okButton = (Button) lDialog.findViewById(R.id.ok);
        okButton.setVisibility(View.GONE);
        final Button maleButton = (Button)lDialog.findViewById(R.id.dialog_male);
        final Button femaleButton = (Button)lDialog.findViewById(R.id.dialog_female);
        if (genderView.getText().equals(getString(R.string.male))){
            dialogRadioGroup.check(R.id.dialog_male);
        }else
            dialogRadioGroup.check(R.id.dialog_female);
        maleButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                genderView.setText(maleButton.getText());
                lDialog.dismiss();
            }
        });

        femaleButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                genderView.setText(femaleButton.getText());
                lDialog.dismiss();
            }
        });

        ((Button) lDialog.findViewById(R.id.cancel))
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        lDialog.dismiss();
                    }
                });
        lDialog.show();
    }

    @Override
    public void onInputDialogTextDone(String text, int type) {
        switch (type) {
            case REQUEST_EDIT_DES:
                desEdit.setText(text);
                break;
            case REQUEST_EDIT_NICK:
                nickEdit.setText(text);
                break;
        }
    }

    /**
     * This class contains all butterknife-injected Views & Layouts from layout file
     * 'edit_profile_list_item.xml'
     * for easy to all layout elements.
     *
     * @author ButterKnifeZelezny, plugin for Android Studio by Avast Developers (http://github
     *         .com/avast)
     */
    static class ViewHolder {
        @Bind(R.id.title)
        TextView title;

        @Bind(R.id.arrow)
        ImageView arrow;

        @Bind(R.id.bind)
        TextView bind;

        @Bind(R.id.content)
        TextView content;

        @Bind(R.id.avatar)
        CircleImageView avatar;

        @Bind(R.id.divider)
        View divider;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case ImageUtils.TAKE_OR_CHOOSE_PHOTO:
                File f = ImageUtils.getPhotoFromResult(this, data);
                ImageUtils.doCropPhoto(this, f);
                break;
            case ImageUtils.PHOTO_PICKED_WITH_DATA:
                bitmap = ImageUtils.getCroppedImage();
                avatar.setBorderColor(Global.avatarColor);
                avatar.setBorderWidth(2);
                avatar.setImageBitmap(bitmap);
                if (bitmap!=null){
                    updateAvatar(bitmap);
                }
                break;
            case REQUEST_VERIFY_MOBILE:
                String verifyCode = data.getStringExtra("code");
                String cellphone = data.getStringExtra("cellphone");
                afterLogin(VALUE_APP, cellphone, verifyCode);
                break;
        }
    }

    private void updateAvatar(final Bitmap bitmap) {
       /* new RequestServerTask<AvatarResponse>(AvatarResponse.class) {
            @Override
            protected String requestServer() {
                Map<String, Object> map = new HashMap<>();
                map.put("uid",Global.getCurrentUid());
                ImageUtils.saveAvatar(bitmap,EditProfileActivity.this);
                File avatarFile = FileUtils.getAvatarFile();
                map.put("user_pic", avatarFile);
                String url = String.format(NetworkConstants.UPDATE_AVATAR_URL, Global
                        .getCurrentUid());
                return HttpUtil.post(url,null,map,null);

            }

            @Override
            protected void onSuccess(AvatarResponse result) {
                Utils.showToast(R.string.change_avatar_success);
                Global.currentUser.pic = result.data;
            }
        }.start();*/

        String url = String.format(NetworkConstants.UPDATE_AVATAR_URL, Global.getCurrentUid());
        UploadImageRequest request = new UploadImageRequest(this, url, "user_pic",
                bitmap, new UploadImageRequest.ResultListener() {
            @Override
            public void onSuccess(String msg) {}

            @Override
            public void onFailure(String msg) {
                Toast.makeText(EditProfileActivity.this, msg, Toast.LENGTH_SHORT).show();
            }
        });
        request.execute();
    }

    private void updateProfile() {
        new RequestServerTask<LogInResponse>(LogInResponse.class) {

            @Override
            protected String requestServer() {
                Map<String, Object> map = new HashMap<>();
                map.put("uid", Global.getCurrentUid());
                map.put("sex", User.getGenderValue(genderView.getText().toString()));
                map.put("des", desEdit.getText().toString());
                map.put("nick", nickEdit.getText().toString());
                map.put("birth",birthdayView.getText().toString() + " 00:00:00");
                Log.d("birthday",birthdayView.getText().toString());
                String url = String.format(NetworkConstants.UPDATE_PROFILE_URL, Global
                        .getCurrentUid());
                return HttpUtil.post(url, map);
            }

            @Override
            protected void onSuccess(LogInResponse result) {
                Utils.showToast(R.string.update_profile_success);
                //result.data.token = Global.currentUser.token;
                //saveUserInfo(result);


                int uid = Global.getCurrentUid();
                String token = Global.currentUser.token;
                String p_nick = Global.currentUser.p_nick;
                Settings.delUser(String.valueOf(uid));
                Settings.setCurrentUid(0);
                Global.currentUser = null;
                saveUserInfo(result,token,p_nick);
            }
        }.start();
    }

    public static final String BINDING = "binding";

    public static final String UNBINDING = "unbinding";

    @Override
    protected void afterLogin(int type, String uid, String token) {
        String url;
        Map<String, Object> params = new HashMap<>();
        switch (type) {
            case VALUE_QQ:
                url = String.format(NetworkConstants.BIND_QQ_URL, String.valueOf(Global
                        .getCurrentUid()));
                params.put("type", Global.currentUser.is_QQ ? UNBINDING : BINDING);
                params.put("uid", uid);
                params.put("token", token);
                break;
            case VALUE_SINA:
                url = String.format(NetworkConstants.BIND_WEIBO_URL, String.valueOf(Global
                        .getCurrentUid()));
                params.put("type", TextUtils.isEmpty(Global.currentUser.weibo) ? BINDING :
                        UNBINDING);
                params.put("uid", uid);
                params.put("token", token);
                break;
            case VALUE_WECHAT:
                url = String.format(NetworkConstants.BIND_WECHAT_URL, String.valueOf(Global
                        .getCurrentUid()));
                params.put("type", TextUtils.isEmpty(Global.currentUser.weixin) ? BINDING :
                        UNBINDING);
                Log.d("EditProfile",TextUtils.isEmpty(Global.currentUser.weixin)+"  code:"+uid);
                params.put("code", uid);
                params.put("token", token);
                break;
            case VALUE_APP:
                url = String.format(NetworkConstants.BIND_MOBILE_URL, String.valueOf(Global
                        .getCurrentUid()));
                params.put("type", Global.currentUser.is_phone ? UNBINDING : BINDING);
                params.put("cellphone", uid);
                if (token != null) {
                    params.put("code", token);
                }
                break;
            default:
                return;
        }

        updateBindingStatus(url, params);
    }

    private boolean isWeiboUser() {
        return !TextUtils.isEmpty(Global.currentUser.weibo);
    }

    private boolean isWeChatUser() {
        return !TextUtils.isEmpty(Global.currentUser.weixin);
    }



}
